package com.gitee.hermer.engine.jars.demo.boot;

import java.io.IOException;

import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.gitee.hermer.engine.jars.app.sdk.annotate.EnableEngineScan;
import com.gitee.hermer.engine.jars.dependent.dozer.annotate.EnableDozer;

@Configuration
@EnableEngineScan(basePackages = {"com.topisv.wms"})
@ComponentScan(basePackages = {"com.topisv.wms","house.jc.engine.execute"}, excludeFilters = { @Filter(Controller.class), @Filter(Configuration.class) })
@Order(Ordered.HIGHEST_PRECEDENCE+1000)
@EnableScheduling
@EnableDozer("classpath*:dozer/*.xml")
public class SpringRootConfig{
	
	@Bean
	public JobFactory jobFactory(ApplicationContext applicationContext) {
		AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
		jobFactory.setApplicationContext(applicationContext);
		return jobFactory;
	}
	@Bean
	public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws IOException {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		factory.setAutoStartup(true);
		factory.setJobFactory(jobFactory);
		return factory;
	}
	public static class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
	ApplicationContextAware {

		private transient AutowireCapableBeanFactory beanFactory;

		@Override
		public void setApplicationContext(final ApplicationContext context) {
			beanFactory = context.getAutowireCapableBeanFactory();
		}

		@Override
		protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
			final Object job = super.createJobInstance(bundle);
			beanFactory.autowireBean(job);
			return job;
		}
	}

}
